package com.dms.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class DBUtil {
    private Connection con=null;
    private Statement state = null;
    private PreparedStatement pstate = null;
    private  ResultSet res = null;  
    private final static String DRIVER = "com.mysql.jdbc.Driver";
    private static String URL;
    private static String NAME;
    private static String PASSWORD;
    
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
        	e.printStackTrace();
        }
    }
    
    public DBUtil() {
    	Properties config = new Properties();//属性集合对象    
        FileInputStream fis;
		try {			
			fis = new FileInputStream(getClass().getResource("/").getPath()+"/config/db.properties");	
			config.load(fis);
	        URL = config.getProperty("URL");
	        NAME = config.getProperty("NAME");
			PASSWORD = config.getProperty("PASSWORD");
	        fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//属性文件流
            //将属性文件流装载到Properties对象中   
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    public Connection getConnection() {
        try {
            con =  DriverManager.getConnection(URL, NAME, PASSWORD);
        } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return con;
    }

    public  void close() throws SQLException {
        if (res != null) {
            res.close();
        }
        if (state != null) {
            state.close();
        }
        if(pstate != null){
            pstate.close();
        }
        if (con != null) {
            con.close();
        }
    }
    
    public ResultSet query(String sqlString)throws Exception{
        pstate = createStatement(sqlString);
        res=pstate.executeQuery();
        return res;
    }
    
    
    public ResultSet query(String sqlString, Object... params)throws Exception{
        pstate = createStatement(sqlString, params);
        res=pstate.executeQuery();
        return res;
    }
    
    public int update(String sqlString, Object... params)throws Exception{
        pstate = createStatement(sqlString, params);
        return pstate.executeUpdate();
    }

    private PreparedStatement createStatement(String sqlString, Object... params) throws SQLException {
        pstate = getConnection().prepareStatement(sqlString);
        for (int i = 0; i < params.length; i++) {
            Object param = params[i];
            pstate.setObject(i+1, param);
        }
        return pstate;
    }
}
